package com.smartbands.manage.interceptor;

import com.alibaba.fastjson.JSONObject;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.smartbands.common.entity.User;
import com.smartbands.common.enums.ResultCodeEnum;
import com.smartbands.common.util.JwtUtil;
import com.smartbands.manage.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

/**
 * 使用拦截骑拦截请求，验证token
 *
 * @author mtf
 * @create 2021-01-29-10:41
 */
@Component
@Slf4j
public class JWTInterceptor implements HandlerInterceptor {
    @Autowired
    private UserService userService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        log.info("进入拦截器");
        log.info("request请求地址path[{}] uri[{}]", request.getServletPath(), request.getRequestURI());
        try {
            response.setCharacterEncoding("UTF-8");
            response.setContentType("application/json; charset=utf-8");
            JSONObject res = new JSONObject();
            PrintWriter printWriter = response.getWriter();
            String token = request.getHeader("token");
            if (StringUtils.isBlank(token)) {
                log.info("无token认证信息，请登陆");
                res.put("status", ResultCodeEnum.FAIL.code());
                res.put("message", "用户未登录！");
                printWriter.append(res.toString());
                return false;
            } else {
                String userId = JwtUtil.getUserId(token);
                // 添加request参数，用于传递userid
                request.setAttribute("userId", userId);
                // 根据userId 查询用户信息
                User user = userService.getByUserId(userId);
                if (user == null) {
                    throw new RuntimeException("用户不存在，请重新登录");
                }
                // 验证 密码
                JwtUtil.verify(token,user.getPassword());
                return true;
            }
        } catch (Exception e) {
            log.error(e.getMessage());
            response.sendError(500);
            return false;
        }
    }
}
